package controller;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import jpa.exceptions.NonexistentEntityException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import model.Comment;
import model.CommentQuery;
import model.Event;
import model.EventQuery;
import model.HistoryPayment;
import model.HistoryPaymentQuery;
import model.UserQuery;
import model.User;

/**
 *
 * @author Kelompok 3
 * Kelas ini berfungsi untuk menghubungkan parameter pada bagian view
 * dengan fungsi-fungsi yang sudah dibuat pada kelas Daftar User sehingga
 * dapat dilakukan proses timbal balik antara user dan sistem
 * 
 */
public class AccountLogic {

    HttpServletRequest request;

    public AccountLogic(HttpServletRequest request) {
        this.request = request;
    }


    /* method untuk melakukan fungsi sign up, yaitu mengambil nilai textfield pada form registrasi
     * untuk kemudian dimasukkan sebagai nilai untuk membuat baris baru pada tabel users
     */
    public String signUp() throws NoSuchAlgorithmException {
        User user = new User();
        UserQuery uq = new UserQuery();
        List<Event> events = new ArrayList<Event>();
        /*buat nampilin event yang diliat oleh vieweer */
        EventQuery eq = new EventQuery();
        HttpSession session = request.getSession();

        String nama = request.getParameter("nama");
        String alamat = request.getParameter("alamat");
        String telepon = request.getParameter("telepon");
        String email = request.getParameter("email");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");

        if (username != null) {
            user.setNama(nama);
            user.setAlamat(alamat);
            user.setTelepon(telepon);
            user.setEmail(email);
            user.setUsername(username);
            MessageDigest mdEnc = MessageDigest.getInstance("MD5"); // Encryption algorithm
            mdEnc.update(password.getBytes(), 0, password.length());
            String md5 = new BigInteger(1, mdEnc.digest()).toString(16); // Encrypted string
            user.setPassword(md5);
            user.setAdminStat(0);
            session.setAttribute("tempReg", user);
        } else {
            session.setAttribute("error", "masih ada field kosong");
            return "register.jsp";
        }

        /*memberikan pesan eror saat ada field yang kosong*/
        if (nama.equals("") || alamat.equals("") || telepon.equals("")
                || email.equals("") || username.equals("") || password.equals("")) {
            session.setAttribute("error", "masih ada field kosong");
            return "register.jsp";
        }/*memberikan validasi pada inputan*/ else {
            if (password.equals(confirmPassword)) {
                /*memberikan pesan eror saat ada inputan pada textfield telp selain angka*/
                try {
                    int telp = Integer.parseInt(telepon);
                } catch (NumberFormatException nfe) {
                    session.setAttribute("error", "format telepon harus angka");
                    return "register.jsp";
                }
                if (password.length() > 5) {
                    boolean hasilCheck = uq.checkUser(username);
                    if (!hasilCheck) {
                        uq.createPromotor(user);
                        session.removeAttribute("uname");/*antisipasi jika udah login tapi masuk link register */
                        session.removeAttribute("tempReg");/*menampilkan pesan error namun tidak kosong inputannya*/
                        events = eq.getLimitedEvents();
                        request.setAttribute("events", events);/*kanan nilai, kiri nama*/
                        session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
                        return "index.jsp";
                    }/*memberikan pesan eror saat ada username yang sama dengan database */ else {
                        session.setAttribute("error", "username sudah terpakai");
                        return "register.jsp";
                    }
                } /*memberikan pesan eror saat password kurang dari 6*/ else {
                    session.setAttribute("error", "password minimal 6");
                    return "register.jsp";
                }
            } else {
                session.setAttribute("error", "konfirmasi password salah");
                return "register.jsp";
            }
        }
    }


    /* method ini berguna untuk meredirect user menuju halaman profil
     * dengan syarat session tidak dalam keadaan null
     */
    public String lihatProfil() {
        HttpSession session = request.getSession();
        User user = new User();
        UserQuery uq = new UserQuery();
        List<Event> events = new ArrayList<Event>();
        EventQuery eq = new EventQuery();
        if (session.getAttribute("uname") != null) { /*ngecek apakah udah kehapus atau belum*/
            User uname = (User) session.getAttribute("uname");
            String username = uname.getUsername();
            boolean hasilCheck = uq.checkUser(username);
            /* melakukan pengecekan AdminStat*/
            if (hasilCheck) {
                user = uname;
                /*redirect ke halaman profil Administrator jika admin status = 1*/
                if (user.getAdminStat() == 1) {
                    return "profilAdmin.jsp";
                }/*redirect ke halaman profil Promotor jika admin status = 0*/ else {
                    return "profil.jsp";
                }
            }/*redirect ke halaman utama jika username tidak ditemukan*/ else {
                session.setAttribute("error", "username tidak ada");
                events = eq.getLimitedEvents();
                request.setAttribute("events", events);
                session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
                return "index.jsp";
            }
        } else {
            session.setAttribute("error", "sudah logout sebelumnya");
            events = eq.getLimitedEvents();
            request.setAttribute("events", events);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
            return "index.jsp";
        }
    }

    /* method ini berguna untuk meredirect user menuju halaman profil promotor 
     * yang bisa dilihat umum dengan syarat session tidak dalam keadaan null
     */
    public String lihatProfilPublic() {/*buat liat promotor public id ome*/
        HttpSession session = request.getSession();
        User user = new User();
        UserQuery uq = new UserQuery();
        String temp = request.getParameter("idUser");
        int idUser = Integer.parseInt(temp);
        user = uq.getUser(idUser);
        request.setAttribute("user", user);
        return "profilPublic.jsp";
    }

    /* method untuk melakukan fungsi login yaitu mengecek apakah username dan password 
     * yang dimasukkan ke dalam form login sudah sesuai
     */
    public String loggedIn() throws NoSuchAlgorithmException {
        HttpSession session = request.getSession();
        User user = new User();
        UserQuery uq = new UserQuery();
        List<Event> events = new ArrayList<Event>();
        EventQuery eq = new EventQuery();
        String username = request.getParameter("username");
        String md5 = request.getParameter("password");
        MessageDigest mdEnc = MessageDigest.getInstance("MD5"); // Encryption algorithm
        mdEnc.update(md5.getBytes(), 0, md5.length());
        String password = new BigInteger(1, mdEnc.digest()).toString(16); // Encrypted string
        if (username != null) {
            user.setUsername(username);
            session.setAttribute("tempLog", user);
        } else {
            session.setAttribute("error", "masih ada field kosong");
            events = eq.getLimitedEvents();
            request.setAttribute("events", events);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
            return "index.jsp";
        }
        if (session.getAttribute("uname") == null) {
            if (username.equals("") || password.equals("")) {
                session.setAttribute("error", "masih ada field kosong");
                events = eq.getLimitedEvents();
                request.setAttribute("events", events);
                session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
                return "index.jsp";
            } else {
                boolean hasilCheck = uq.checkUser(username);
                if (hasilCheck) {
                    user = null;
                    user = uq.getUser(username);

                    if (username.equals(user.getUsername()) && password.equals(user.getPassword())) {
                        session.setAttribute("uname", user);
                        session.removeAttribute("tempLog");
                        if (user.getAdminStat() == 1) {
                            return "profilAdmin.jsp";
                        } else {
                            return "profil.jsp";
                        }
                    } else {
                        session.setAttribute("error", "username/password salah");
                        events = eq.getLimitedEvents();
                        request.setAttribute("events", events);
                        session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
                        return "index.jsp";
                    }
                } else {
                    session.setAttribute("error", "username tidak ada");
                    events = eq.getLimitedEvents();
                    request.setAttribute("events", events);
                    session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
                    return "index.jsp";
                }
            }
        } else {
            User uname = (User) session.getAttribute("uname");
            /*redirect ke halaman profil Administrator jika admin status = 1*/
            if (uname.getAdminStat() == 1) {
                return "profilAdmin.jsp";
            }/*redirect ke halaman profil Promotor jika admin status = 0*/ else {
                return "profil.jsp";
            }
        }
    }


    /* method untuk logout yaitu dengan cara
     * menghapus session sehingga session kembali menjadi null
     */
    public String logout() {
        HttpSession session = request.getSession();
        List<Event> events = new ArrayList<Event>();
        EventQuery eq = new EventQuery();
        if (session.getAttribute("uname") != null) {
            session.removeAttribute("ename");
            session.removeAttribute("uname");
            events = eq.getLimitedEvents();
            request.setAttribute("events", events);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
            return "index.jsp";
        } else {
            session.setAttribute("error", "sudah logout sebelumnya");
            events = eq.getLimitedEvents();
            request.setAttribute("events", events);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
            return "index.jsp";
        }
    }


    /* method untuk meredirect user menuju halaman editProfil dengan
     * syarat session tidak dalam keadaan null
     */
    public String ubahProfil() {
        HttpSession session = request.getSession();
        User user = new User();
        UserQuery uq = new UserQuery();
        List<Event> events = new ArrayList<Event>();
        EventQuery eq = new EventQuery();

        if (session.getAttribute("uname") != null) {
            User uname = (User) session.getAttribute("uname");
            boolean hasilCheck = uq.checkUser(uname.getUsername());
            if (hasilCheck) {
                user = uname;
                session.setAttribute("tempEdit", user);
                return "editProfil.jsp";
            } else {
                session.setAttribute("error", "username tidak ada");
                events = eq.getLimitedEvents();
                request.setAttribute("events", events);
                session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
                return "index.jsp";
            }
        } else {
            session.setAttribute("error", "sudah logout sebelumnya");
            events = eq.getLimitedEvents();
            request.setAttribute("events", events);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
            return "index.jsp";
        }
    }


    /* method untuk menyimpan perubahan data profil user
     * yaitu mengupdate nilai lama dengan nilai yang baru saja dimasukkan
     * saat mengisi form pada halaman editProfil
     */
    public String simpanUbahProfil() throws NoSuchAlgorithmException {
        HttpSession session = request.getSession();
        User user = new User();
        UserQuery uq = new UserQuery();
        List<Event> events = new ArrayList<Event>();
        EventQuery eq = new EventQuery();

        String nama = request.getParameter("nama");
        String alamat = request.getParameter("alamat");
        String telepon = request.getParameter("telepon");
        String email = request.getParameter("email");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        if (session.getAttribute("uname") != null) {
            user = (User) session.getAttribute("uname");
            String tempUname = user.getUsername();
            if (username != null) {
                user.setNama(nama);
                user.setAlamat(alamat);
                user.setTelepon(telepon);
                user.setEmail(email);
                user.setUsername(username);
                MessageDigest mdEnc = MessageDigest.getInstance("MD5"); // Encryption algorithm
                mdEnc.update(password.getBytes(), 0, password.length());
                String md5 = new BigInteger(1, mdEnc.digest()).toString(16); // Encrypted string
                user.setPassword(md5);
                session.setAttribute("tempEdit", user);
            } else {
                session.setAttribute("error", "masih ada field kosong");
                return "editProfil.jsp";
            }

            if (nama.equals("") || alamat.equals("") || telepon.equals("")
                    || email.equals("") || password.equals("")) {
                session.setAttribute("error", "masih ada field kosong");
                return "editProfil.jsp";
            } else {
                if (password.equals(confirmPassword)) {

                    try {
                        int telp = Integer.parseInt(telepon);
                    } catch (NumberFormatException nfe) {
                        session.setAttribute("error", "format telepon harus angka");
                        return "editProfil.jsp";
                    }
                    if (password.length() > 5) {
                        boolean hasilCheck = uq.checkUser(username);
                        if (!hasilCheck || username.equals(tempUname)) {
                            session.setAttribute("uname", user);
                            uq.editUser(user);
                            session.removeAttribute("tempEdit");
                            if (user.getAdminStat() == 1) {
                                return "profilAdmin.jsp";
                            } else {
                                return "profil.jsp";
                            }
                        } else {
                            session.setAttribute("error", "username sudah terpakai");
                            return "editProfil.jsp";
                        }
                    } else {
                        session.setAttribute("error", "password minimal 6");
                        return "editProfil.jsp";
                    }
                } else {
                    session.setAttribute("error", "konfirmasi password salah");
                    return "editProfil.jsp";
                }
            }
        } else {
            session.setAttribute("error", "sudah logout sebelumnya");
            events = eq.getLimitedEvents();
            request.setAttribute("events", events);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
            return "index.jsp";
        }
    }


    /* method untuk menghapus promotor berdasarkan id dari promotor bersangkutan
     */
    public String hapusPromotor() throws NonexistentEntityException {
        HttpSession session = request.getSession();
        String idUser = request.getParameter("idUser");
        List<User> users = new ArrayList<User>();
        UserQuery uq = new UserQuery();
        List<Event> events = new ArrayList<Event>();
        EventQuery eq = new EventQuery();
        List<Comment> comments = new ArrayList<Comment>();
        CommentQuery cq = new CommentQuery();
        List<HistoryPayment> historyPayments = new ArrayList<HistoryPayment>();
        HistoryPaymentQuery hpq = new HistoryPaymentQuery();

        if (session.getAttribute("uname") != null) {
            if (idUser == null) {
                users = uq.getPromotors();
                request.setAttribute("users", users);
            } else {
                int id = Integer.parseInt(idUser);
                User temp = uq.getUser(id);
                events = eq.getMyEvents(temp);
                if (events != null) {
                    Iterator<Event> iteratorE = events.iterator();
                    while (iteratorE.hasNext()) {
                        Event nextE = iteratorE.next();
                        comments = cq.getComments(nextE);
                        if (comments != null) {
                            Iterator<Comment> iteratorC = comments.iterator();
                            while (iteratorC.hasNext()) { /*gak mesti yang dihapus cuma 1 baris*/
                                Comment nextC = iteratorC.next();
                                cq.deleteComment(nextC.getIdComment());
                            }
                        }
                        historyPayments = hpq.getHistoryPayments(nextE);
                        if (historyPayments != null) {
                            Iterator<HistoryPayment> iteratorH = historyPayments.iterator();
                            while (iteratorH.hasNext()) {
                                HistoryPayment nextH = iteratorH.next();
                                hpq.deleteHistoryPayment(nextH.getIdPayment());
                            }
                        }
                        eq.deleteEvent(nextE.getIdEvent());
                    }
                }
                uq.deletePromotor(id);
                users = uq.getPromotors();
                request.setAttribute("users", users);
            }
            return "daftarPromotor.jsp";
        } else {
            session.setAttribute("error", "sudah logout sebelumnya");
            events = eq.getLimitedEvents();
            request.setAttribute("events", events);
            session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
            return "index.jsp";
        }
    }
    /*method untuk membuka welcome page
     */

    public String home() {
        HttpSession session = request.getSession();
        List<Event> events = new ArrayList<Event>();
        EventQuery eq = new EventQuery();
        String show;
        if (request.getParameter("show") != null) {
            show = request.getParameter("show");
        } else {
            show = "limited";
        }
        session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
        if (session.getAttribute("uname") == null) {
            if (show.equals("all")) {
                events = eq.getAllEvents();
                request.setAttribute("events", events);
                session.setAttribute("show", "<a href='account?page=home'>Five Recent Events</a>");
                return "index.jsp";
            } else {
                events = eq.getLimitedEvents();
                request.setAttribute("events", events);
                session.setAttribute("show", "<a href='account?page=home&&show=all'>Show All Events</a>");
                return "index.jsp";
            }
        } else {
            if (show.equals("all")) {
                events = eq.getAllEvents();
                request.setAttribute("events", events);
                session.setAttribute("show", "<a href='account?page=home'>Five Recent Events</a>");
                return "home.jsp";
            } else {
                events = eq.getLimitedEvents();
                request.setAttribute("events", events);
                session.setAttribute("show", "<a href='account?page=home&&show=all'>show all events</a>");
                return "home.jsp";
            }
        }
    }
}
